package top.luqichuang.common.jsoup;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import top.luqichuang.common.util.StringUtil;

/**
 * @author LuQiChuang
 * @desc
 * @date 2020/8/12 15:25
 * @ver 1.0
 */
public class JsoupStarter<T> {

    private JsoupNode node = new JsoupNode();

    /**
     * 章节顺序 默认为倒序
     *
     * @return boolean
     */
    protected boolean isDESC() {
        return true;
    }

    /**
     * 处理漫画基本信息
     *
     * @param node node
     * @return void
     */
    protected void dealInfo(JsoupNode node) {
    }

    /**
     * 处理章节信息
     *
     * @param node node
     * @return T
     */
    protected T dealElement(JsoupNode node) {
        return null;
    }

    /**
     * 处理info
     *
     * @param html html
     * @return void
     */
    public final void startInfo(String html) {
        node.init(html);
        dealInfo(node);
    }

    /**
     * 根据cssQuery查询到对应单个数据块(div、li等)
     *
     * @param html     html
     * @param cssQuery 查询到div、li等
     * @return List<T>
     */
    public final List<T> startElements(String html, String... cssQuery) {
        node.init(html);
        List<T> list = new ArrayList<>();
        Elements elements = null;
        for (String s : cssQuery) {
            elements = node.getElements(s);
            if (!elements.isEmpty()) {
                break;
            }
        }
        if (elements == null) {
            return list;
        }
        for (Element element : elements) {
            node.init(element);
            T t = dealElement(node);
            if (t != null) {
                list.add(t);
            }
        }
        if (!isDESC()) {
            StringUtil.swapList(list);
        }
        return list;
    }

}
